<template>
  <div class="schedule-page">
    <div class="page-header">
      <h2>创建排期</h2>
      <div class="header-subtitle">为广告创建播放排期</div>
    </div>

    <el-card class="schedule-form-card">
      <el-form :model="scheduleForm" :rules="rules" ref="scheduleFormRef" label-width="100px">
        <el-form-item label="协商信息" v-if="negotiation">
          <div class="negotiation-info">
            <div class="info-item">
              <span class="label">广告名称:</span>
              <span class="value">{{ negotiation.advertisementName }}</span>
            </div>
            <div class="info-item">
              <span class="label">广告主:</span>
              <span class="value">{{ negotiation.advertiserName }}</span>
            </div>
            <div class="info-item">
              <span class="label">设备名称:</span>
              <span class="value">{{ negotiation.deviceName }}</span>
            </div>
            <div class="info-item">
              <span class="label">协商价格:</span>
              <span class="value price">¥{{ negotiation.price }}</span>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="播放日期" prop="dateRange">
          <el-date-picker
            v-model="scheduleForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :disabled-date="disablePastDates"
          />
        </el-form-item>

        <el-form-item label="播放时段">
          <div v-for="(slot, index) in scheduleForm.timeSlots" :key="index" class="time-slot-item">
            <el-time-picker
              v-model="slot.startTimeObj"
              format="HH:mm"
              placeholder="开始时间"
              @change="updateTimeSlotString(slot, 'start')"
            />
            <span class="time-separator">至</span>
            <el-time-picker
              v-model="slot.endTimeObj"
              format="HH:mm"
              placeholder="结束时间"
              @change="updateTimeSlotString(slot, 'end')"
            />
            <el-button 
              type="danger" 
              circle 
              icon="Delete"
              @click="removeTimeSlot(index)"
              v-if="scheduleForm.timeSlots.length > 1"
            />
          </div>
          <el-button type="primary" plain icon="Plus" @click="addTimeSlot" class="add-slot-btn">
            添加时段
          </el-button>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="scheduleForm.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitSchedule" :loading="submitting">创建排期</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog
      v-model="showConflictDialog"
      title="排期冲突检测"
      width="500px"
    >
      <div class="conflict-info">
        <el-alert
          type="warning"
          :closable="false"
          show-icon
        >
          <p>检测到以下时间段与现有排期存在冲突：</p>
        </el-alert>
        <div class="conflict-list">
          <div v-for="(conflict, index) in conflicts" :key="index" class="conflict-item">
            <span class="conflict-date">{{ conflict.date }}</span>
            <span class="conflict-time">{{ conflict.startTime }} - {{ conflict.endTime }}</span>
            <span class="conflict-ad">与广告 "{{ conflict.adName }}" 冲突</span>
          </div>
        </div>
        <p class="conflict-question">是否调整时间后重试？</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showConflictDialog = false">调整时间</el-button>
          <el-button type="primary" @click="forceSubmitSchedule">
            强制创建排期
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import { getNegotiationDetail } from '@/api/negotiation';
import { createSchedule, getDeviceSchedule } from '@/api/schedule';

const router = useRouter();
const route = useRoute();
const negotiationId = route.params.id;

const scheduleFormRef = ref(null);
const negotiation = ref(null);
const submitting = ref(false);
const showConflictDialog = ref(false);
const conflicts = ref([]);

// 表单数据
const scheduleForm = reactive({
  negotiationId: negotiationId,
  advertisementId: null,
  deviceId: null,
  dateRange: [],
  timeSlots: [
    {
      startTimeObj: null,
      endTimeObj: null,
      startTime: '',
      endTime: ''
    }
  ],
  remark: ''
});

// 表单验证规则
const rules = {
  dateRange: [
    { required: true, message: '请选择播放日期范围', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (!value || value.length < 2) {
          callback(new Error('请选择开始和结束日期'));
        } else {
          const [start, end] = value;
          if (new Date(start) > new Date(end)) {
            callback(new Error('结束日期不能早于开始日期'));
          } else {
            callback();
          }
        }
      }, 
      trigger: 'change' 
    }
  ]
};

// 禁用过去的日期
const disablePastDates = (date) => {
  return date < new Date(new Date().setHours(0, 0, 0, 0));
};

// 获取协商详情
const fetchNegotiationDetail = async () => {
  try {
    const res = await getNegotiationDetail(negotiationId);
    if (res.data.code === 200) {
      negotiation.value = res.data.data;
      console.log('获取协商详情', res);
      
      // 填充表单数据
      scheduleForm.advertisementId = negotiation.value.adId;
      scheduleForm.deviceId = negotiation.value.deviceId;

      console.log('获取协商详情', scheduleForm.advertisementId,scheduleForm.deviceId);

      
      // 如果协商中有时间段信息，预填充表单
      if (negotiation.value.timeSlots && negotiation.value.timeSlots.length > 0) {
        scheduleForm.timeSlots = [];
        negotiation.value.timeSlots.forEach(slot => {
          const [hours, minutes] = slot.startTime.split(':');
          const startTimeObj = new Date();
          startTimeObj.setHours(parseInt(hours), parseInt(minutes), 0);
          
          const [endHours, endMinutes] = slot.endTime.split(':');
          const endTimeObj = new Date();
          endTimeObj.setHours(parseInt(endHours), parseInt(endMinutes), 0);
          
          scheduleForm.timeSlots.push({
            startTimeObj,
            endTimeObj,
            startTime: slot.startTime,
            endTime: slot.endTime
          });
        });
      }
    } else {
      ElMessage.error(res.message || '获取协商详情失败');
      router.back();
    }
  } catch (error) {
    console.error('获取协商详情失败', error);
    ElMessage.error('获取协商详情失败');
    router.back();
  }
};

// 添加时间段
const addTimeSlot = () => {
  scheduleForm.timeSlots.push({
    startTimeObj: null,
    endTimeObj: null,
    startTime: '',
    endTime: ''
  });
};

// 移除时间段
const removeTimeSlot = (index) => {
  scheduleForm.timeSlots.splice(index, 1);
};

// 更新时间段字符串
const updateTimeSlotString = (slot, type) => {
  if (type === 'start' && slot.startTimeObj) {
    const hours = slot.startTimeObj.getHours().toString().padStart(2, '0');
    const minutes = slot.startTimeObj.getMinutes().toString().padStart(2, '0');
    slot.startTime = `${hours}:${minutes}`;
  } else if (type === 'end' && slot.endTimeObj) {
    const hours = slot.endTimeObj.getHours().toString().padStart(2, '0');
    const minutes = slot.endTimeObj.getMinutes().toString().padStart(2, '0');
    slot.endTime = `${hours}:${minutes}`;
  }
};

// 检查时间段是否有效
const validateTimeSlots = () => {
  const invalidSlots = scheduleForm.timeSlots.filter(slot => {
    if (!slot.startTimeObj || !slot.endTimeObj) {
      return true;
    }
    return slot.startTimeObj >= slot.endTimeObj;
  });
  
  if (invalidSlots.length > 0) {
    ElMessage.error('时间段设置无效，结束时间必须晚于开始时间');
    return false;
  }
  
  return true;
};

// 检查排期冲突
const checkScheduleConflicts = async () => {
  if (!scheduleForm.dateRange || scheduleForm.dateRange.length < 2) {
    return false;
  }
  
  try {
    const [startDate, endDate] = scheduleForm.dateRange;
    const res = await getDeviceSchedule(scheduleForm.deviceId, startDate, endDate);
    
    if (res.data.code === 200) {
      const existingSchedules = res.data.data;
      conflicts.value = [];
      
      // 检查冲突
      if (existingSchedules && existingSchedules.length > 0) {
        for (const existingSchedule of existingSchedules) {
          // 跳过与当前广告相同的排期
          if (existingSchedule.advertisementId === scheduleForm.advertisementId) {
            continue;
          }
          
          const scheduleDate = new Date(existingSchedule.date).toLocaleDateString();
          
          for (const existingSlot of existingSchedule.timeSlots) {
            for (const newSlot of scheduleForm.timeSlots) {
              // 转换为分钟便于比较
              const existingStart = timeToMinutes(existingSlot.startTime);
              const existingEnd = timeToMinutes(existingSlot.endTime);
              const newStart = timeToMinutes(newSlot.startTime);
              const newEnd = timeToMinutes(newSlot.endTime);
              
              // 检查是否有重叠
              if ((newStart < existingEnd && newEnd > existingStart)) {
                conflicts.value.push({
                  date: scheduleDate,
                  startTime: existingSlot.startTime,
                  endTime: existingSlot.endTime,
                  adName: existingSchedule.advertisementName
                });
              }
            }
          }
        }
        
        if (conflicts.value.length > 0) {
          showConflictDialog.value = true;
          return true;
        }
      }
      
      return false;
    }
    
    return false;
  } catch (error) {
    console.error('检查排期冲突失败', error);
    return false;
  }
};

// 时间字符串转换为分钟数
const timeToMinutes = (timeStr) => {
  const [hours, minutes] = timeStr.split(':').map(Number);
  return hours * 60 + minutes;
};

// 构建请求数据
const buildScheduleData = () => {
  const [startDate, endDate] = scheduleForm.dateRange;
  
  // 组合日期和时间
  const startDateTime = `${startDate} 00:00:00`;
  const endDateTime = `${endDate} 23:59:59`;
  
  // 准备时间段数据
  const timeSlots = scheduleForm.timeSlots.map(slot => ({
    startTime: slot.startTime,
    endTime: slot.endTime
  }));
  
  return {
    advertisementId: scheduleForm.advertisementId,
    deviceId: scheduleForm.deviceId,
    startTime: startDateTime,
    endTime: endDateTime,
    timeSlots: timeSlots,
    remark: scheduleForm.remark,
    negotiationId : scheduleForm.negotiationId
  };
};

// 提交表单
const submitSchedule = async () => {
  if (!validateTimeSlots()) {
    return;
  }
  
  try {
    await scheduleFormRef.value.validate();
    
    // 检查冲突
    const hasConflicts = await checkScheduleConflicts();
    if (hasConflicts) {
      return;
    }
    
    await doSubmitSchedule();
  } catch (error) {
    console.error('表单验证失败', error);
  }
};

// 强制提交排期（忽略冲突）
const forceSubmitSchedule = async () => {
  showConflictDialog.value = false;
  await doSubmitSchedule(true);
};

// 执行提交
const doSubmitSchedule = async (ignoreConflicts = false) => {
  submitting.value = true;
  
  try {
    const scheduleData = buildScheduleData();
    if (ignoreConflicts) {
      scheduleData.ignoreConflicts = true;
    }
    
    console.info('提交排期数据:', scheduleData);
    const res = await createSchedule(scheduleData);
    console.info(res)
    if (res.data.code === 200) {
      ElMessage.success('排期创建成功');
      
      // 询问是否返回协商列表
      await ElMessageBox.confirm(
        '排期创建成功，是否返回协商列表？',
        '操作成功',
        {
          confirmButtonText: '返回列表',
          cancelButtonText: '留在当前页面',
          type: 'success'
        }
      );
      
      router.push('/device-owner/negotiations');
    } else {
      ElMessage.error(res.message || '创建排期失败');
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户选择留在当前页面
      return;
    }
    console.error('创建排期失败', error);
    ElMessage.error('创建排期失败，请稍后重试');
  } finally {
    submitting.value = false;
  }
};

// 取消操作
const cancel = () => {
  ElMessageBox.confirm(
    '确定要取消创建排期吗？未保存的内容将丢失',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    router.back();
  }).catch(() => {});
};

onMounted(() => {
  fetchNegotiationDetail();
});
</script>

<style scoped>
.schedule-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-subtitle {
  color: #909399;
  font-size: 14px;
  margin-top: 5px;
}

.schedule-form-card {
  margin-bottom: 20px;
}

.negotiation-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  color: #606266;
  width: 80px;
}

.value {
  font-weight: 500;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.time-slot-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}

.time-separator {
  margin: 0 5px;
  color: #909399;
}

.add-slot-btn {
  margin-top: 10px;
}

.conflict-info {
  margin-bottom: 20px;
}

.conflict-list {
  margin-top: 15px;
  max-height: 200px;
  overflow-y: auto;
}

.conflict-item {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
}

.conflict-date {
  font-weight: bold;
}

.conflict-time {
  color: #f56c6c;
  margin: 5px 0;
}

.conflict-ad {
  color: #606266;
  font-size: 13px;
}

.conflict-question {
  margin-top: 15px;
  font-weight: bold;
  text-align: center;
}

@media (max-width: 768px) {
  .negotiation-info {
    grid-template-columns: 1fr;
  }
  
  .time-slot-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .time-separator {
    margin: 5px 0;
  }
}
</style>